package com.example.utils.thread;

import com.example.common.SpringApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;


@Configuration
public class ThreadPoolConfig {


    @Bean("taskExector")
    public ThreadPoolTaskExecutor taskExector() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //获取到服务器的cpu内核
        int i = Runtime.getRuntime().availableProcessors();
        //核心池大小
        executor.setCorePoolSize(5);
        //最大线程数
        executor.setMaxPoolSize(100);
        //队列程度
        executor.setQueueCapacity(1000);
        //线程空闲时间
        executor.setKeepAliveSeconds(1000);
        //线程前缀名称
        executor.setThreadNamePrefix("tsak-asyn");
        //配置拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        return executor;
    }


    /**
     * 使用示例
     * @param args
     */
    public static void main(String[] args) {
        ThreadPoolTaskExecutor executor=SpringApplicationContext.getBeanObj("taskExector");
        executor.execute(new Runnable() {
            @Override
            public void run() {
                System.out.println("我是线程");
            }
        });
    }

}
